package com.example.fanyi

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.BackHandler
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Compare
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.History
import androidx.compose.material.icons.filled.SwapHoriz
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.fanyi.data.TranslationRecord
import com.example.fanyi.ui.theme.FanyiTheme
import com.example.fanyi.viewmodel.TranslationViewModel

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            FanyiTheme {
                TranslationApp()
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TranslationApp(viewModel: TranslationViewModel = viewModel()) {
    var showHistory by remember { mutableStateOf(false) }
    var selectedRecords by remember { mutableStateOf(setOf<TranslationRecord>()) }

    // 处理返回键事件
    BackHandler(enabled = showHistory) {
        showHistory = false
        selectedRecords = emptySet()
    }

    // 统一文字大小
    val textStyle = TextStyle(fontSize = 28.sp)

    Scaffold(
        modifier = Modifier.fillMaxSize(),
        topBar = {
            if (showHistory) {
                CenterAlignedTopAppBar(
                    title = { Text("翻译记录", style = textStyle) },
                    navigationIcon = {
                        IconButton(onClick = { 
                            showHistory = false
                            selectedRecords = emptySet()
                        }) {
                            Icon(
                                imageVector = Icons.Default.ArrowBack,
                                contentDescription = "返回",
                                modifier = Modifier.size(32.dp)
                            )
                        }
                    },
                    actions = {
                        if (selectedRecords.isNotEmpty()) {
                            IconButton(onClick = {
                                viewModel.deleteRecords(selectedRecords)
                                selectedRecords = emptySet()
                            }) {
                                Icon(
                                    imageVector = Icons.Default.Delete,
                                    contentDescription = "删除选中记录",
                                    modifier = Modifier.size(32.dp)
                                )
                            }
                        }
                    }
                )
            }
        }
    ) { innerPadding ->
        if (showHistory) {
            TranslationHistory(
                modifier = Modifier.padding(innerPadding),
                viewModel = viewModel,
                selectedRecords = selectedRecords,
                onSelectionChange = { selectedRecords = it }
            )
        } else {
            TranslationScreen(
                modifier = Modifier.padding(innerPadding),
                viewModel = viewModel,
                onShowHistory = { showHistory = true }
            )
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TranslationScreen(
    modifier: Modifier = Modifier,
    viewModel: TranslationViewModel,
    onShowHistory: () -> Unit
) {
    // 收集状态
    val sourceText by viewModel.sourceText.collectAsState()
    val translatedText by viewModel.translatedText.collectAsState()
    val isChineseToUyghur by viewModel.isChineseToUyghur.collectAsState()
    val errorMessage by viewModel.errorMessage.collectAsState()

    Column(
        modifier = modifier
            .fillMaxSize()
            .verticalScroll(rememberScrollState())
            .padding(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        // 顶部语言切换区域
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceEvenly,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = if (isChineseToUyghur) "汉语" else "维语",
                fontSize = 28.sp
            )
            IconButton(
                onClick = { viewModel.toggleTranslationDirection() },
                modifier = Modifier.size(48.dp)
            ) {
                Icon(
                    imageVector = Icons.Default.SwapHoriz,
                    contentDescription = "切换语言",
                    modifier = Modifier.size(48.dp)
                )
            }
            Text(
                text = if (isChineseToUyghur) "维语" else "汉语",
                fontSize = 28.sp
            )
        }

        Spacer(modifier = Modifier.height(16.dp))

        // 输入框
        OutlinedTextField(
            value = sourceText,
            onValueChange = { viewModel.updateSourceText(it) },
            modifier = Modifier
                .fillMaxWidth()
                .defaultMinSize(minHeight = 200.dp),
            placeholder = {
                Column(modifier = Modifier.fillMaxWidth()) {
                    Text(
                        text = "请输入要翻译的文本",
                        fontSize = 28.sp,
                        textAlign = TextAlign.Start,
                        modifier = Modifier.fillMaxWidth()
                    )
                    Text(
                        text = "تەرجىمە قىلىدىغان تېكىستنى كىرگۈزۈڭ",
                        fontSize = 28.sp,
                        textAlign = TextAlign.End,
                        modifier = Modifier.fillMaxWidth()
                    )
                }
            },
            textStyle = TextStyle(
                fontSize = 28.sp,
                textAlign = if (!isChineseToUyghur) TextAlign.End else TextAlign.Start
            ),
            colors = OutlinedTextFieldDefaults.colors(
                focusedBorderColor = MaterialTheme.colorScheme.primary,
                unfocusedBorderColor = Color.Gray
            ),
            singleLine = false,
            maxLines = Int.MAX_VALUE
        )

        Spacer(modifier = Modifier.height(16.dp))

        // 翻译按钮
        Button(
            onClick = { viewModel.translate() },
            modifier = Modifier.fillMaxWidth()
        ) {
            Text("翻译 تەرجىمە", fontSize = 28.sp)
        }

        Spacer(modifier = Modifier.height(16.dp))

        // 错误信息显示
        if (errorMessage?.isNotEmpty() == true) {
            Text(
                text = errorMessage ?: "",
                color = Color.Red,
                fontSize = 28.sp,
                modifier = Modifier.fillMaxWidth()
            )
            Spacer(modifier = Modifier.height(16.dp))
        }

        // 翻译结果显示
        OutlinedTextField(
            value = translatedText,
            onValueChange = { },
            modifier = Modifier
                .fillMaxWidth()
                .defaultMinSize(minHeight = 200.dp),
            textStyle = TextStyle(
                fontSize = 28.sp,
                textAlign = if (isChineseToUyghur) TextAlign.End else TextAlign.Start
            ),
            readOnly = true,
            colors = OutlinedTextFieldDefaults.colors(
                focusedBorderColor = MaterialTheme.colorScheme.primary,
                unfocusedBorderColor = Color.Gray
            ),
            singleLine = false,
            maxLines = Int.MAX_VALUE
        )

        Spacer(modifier = Modifier.height(16.dp))

        // 翻译记录按钮
        Button(
            onClick = onShowHistory,
            modifier = Modifier.fillMaxWidth()
        ) {
            Text("翻译记录 تەرجىمە خاتىرىسى", fontSize = 28.sp)
        }

        // 底部留出一些空间
        Spacer(modifier = Modifier.height(16.dp))
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TranslationHistory(
    modifier: Modifier = Modifier,
    viewModel: TranslationViewModel,
    selectedRecords: Set<TranslationRecord>,
    onSelectionChange: (Set<TranslationRecord>) -> Unit
) {
    val records by viewModel.translationRecords.collectAsState()
    
    // 统一文字大小
    val textStyle = TextStyle(fontSize = 26.sp)

    LazyColumn(
        modifier = modifier
            .fillMaxSize()
            .padding(16.dp)
    ) {
        items(records) { record ->
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 8.dp),
                onClick = {
                    onSelectionChange(
                        if (selectedRecords.contains(record)) {
                            selectedRecords - record
                        } else {
                            selectedRecords + record
                        }
                    )
                }
            ) {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(16.dp),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Column(modifier = Modifier.weight(1f)) {
                        Text(
                            text = record.sourceText,
                            style = textStyle.copy(
                                textAlign = if (record.isChineseToUyghur) TextAlign.Start else TextAlign.End
                            ),
                            modifier = Modifier.fillMaxWidth()
                        )
                        Spacer(modifier = Modifier.height(8.dp))
                        Text(
                            text = record.translatedText,
                            style = textStyle.copy(
                                textAlign = if (record.isChineseToUyghur) TextAlign.End else TextAlign.Start
                            ),
                            modifier = Modifier.fillMaxWidth()
                        )
                    }
                    if (selectedRecords.contains(record)) {
                        Icon(
                            imageVector = Icons.Default.Delete,
                            contentDescription = "已选中",
                            modifier = Modifier.size(32.dp)
                        )
                    }
                }
            }
        }
    }
}